package cn.tedu._05weibo.common.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException ex){
        String date = ex.getMessage();
        log.error("date="+date);
        return new JsonResult(StatusCode.OPERATION_FAILED,date);
    }

//    @ExceptionHandler
//    public JsonResult doHandlerRuntimeException(RuntimeException ex){
//        String date = ex.getMessage();
//        log.error("date="+date);
//        return JsonResult.fail(date);
//    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("data"+data);
        return new  JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public  JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
//    @ExceptionHandler
//    public  JsonResult throwable(Throwable ex ){
//        String date = ex.getMessage();
//        log.error("date="+date);
//        return new JsonResult(StatusCode.THROWABLE_ERROR,date);
//    }
}
